package com.efounder.frame.manager;

import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.net.Uri;

import com.efounder.util.AppContext;
import com.utilcode.util.LogUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * url schemeManager
 *
 * @author yqs
 */
public class UrlSchemeManager {
    private Intent intent;

    public UrlSchemeManager(Intent intent) {
        this.intent = intent;

    }

    public Uri getUri() {
        return intent.getData();
    }

    public String getScheme() {
        return intent.getScheme();
    }

    public String getHost() {
        return getUri().getHost();
    }

    public int getPort() {
        return getUri().getPort();
    }

    public String getPath() {
        return getUri().getPath();
    }

    public Map<String, String> getQueryMap() {
        Map<String, String> map = new HashMap<>();
        Set<String> paramNames = getUri().getQueryParameterNames();
        for (String key : paramNames) {
            map.put(key, getUri().getQueryParameter(key));
        }
        return map;
    }

    public String getQueryValue(String key) {
        return getUri().getQueryParameter(key);
    }

    public static boolean hasUrlScheme(Intent intent) {
        Uri uri = intent.getData();
        if (uri == null) {
            return false;
        }
        String scheme = intent.getScheme();
        String dataString = intent.getDataString();
        LogUtils.i("UrlScheme:  ", scheme, dataString);
        return true;

        /**
         * caishilive://caishi:8080/loadtooldetail?tool_id=100
         * caishilive：即Scheme 该Scheme协议名称
         * caishi：即Host,代表Scheme作用于哪个地址域
         * 8080：即port，代表端口号
         * loadtooldetail：即path，代表打开的页面
         * tool_id：即query，代表传递的参数

         */

//            //完整的url信息
//            String url = uri.toString();
//            //scheme部分
//            String schemes = uri.getScheme();
//            //host部分
//            String host = uri.getHost();
//            //port部分
//            int port = uri.getPort();
//            //访问路径
//            String path = uri.getPath();
//            //编码路径
//            String path1 = uri.getEncodedPath();
//            //query部分
//            String queryString = uri.getQuery();
//            //获取参数值
//            String systemInfo = uri.getQueryParameter("system");
//            String id = uri.getQueryParameter("id");

    }


    /**
     * 检查拼接的url scheme 是否有效
     *
     * @param intent
     * @return
     */
    public static boolean checkUrlSchemeValid(Intent intent) {
        PackageManager packageManager = AppContext.getInstance().getPackageManager();
        List<ResolveInfo> activities = packageManager.queryIntentActivities(intent, 0);
        return !activities.isEmpty();
    }

}
